package com.coderman.component.kv.scence;

import com.coderman.component.kv.model.KVPairBO;
import com.coderman.component.kv.model.KVParentPair;
import com.coderman.component.kv.service.KVService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 * date: 2022/1/11
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class KVParentService {

    @Resource(name = "kVDBPersistService")
    private KVService kvService;

    /**
     * 获取所有kv对象
     * @return
     */
    public List<KVParentPair> getAllList(){
        List<KVPairBO> kvPairBOList = kvService.getAll();
        return kvPairBOList.stream().map(KVPairBO::convert2ParentPair).collect(Collectors.toList());
    }

    /**
     * 根据分组查询
     * @param groupKey
     * @return
     */
    public List<KVParentPair> getByGroup(String groupKey){
        List<KVPairBO>  kvPairBOList = kvService.getList(KVPairBO.instance().groupKey(groupKey));
        return kvPairBOList.stream().map(KVPairBO::convert2ParentPair).collect(Collectors.toList());
    }

    /**
     * 根据分组查询
     * key:parent
     * @param groupKey
     * @return
     *  key:parentkey
     *  value:kvinstance
     */
    public Map<String,List<KVParentPair>> getKVMapByGroupKey(String groupKey){
        List<KVPairBO>  kvPairBOList = kvService.getList(KVPairBO.instance().groupKey(groupKey));
        List<KVParentPair> kvParentPairList = kvPairBOList.stream().map(KVPairBO::convert2ParentPair).collect(Collectors.toList());
        Map<String,List<KVParentPair>> kvMap = new HashMap<>();
        for (KVParentPair kvParentPair : kvParentPairList){
            List<KVParentPair> kvpList = kvMap.get(kvParentPair.getPstr());
            if(kvpList == null){
                kvpList = new ArrayList<>();
            }
            kvpList.add(kvParentPair);
            kvMap.put(kvParentPair.getPstr(),kvpList);
        }
        return kvMap;
    }

    /**
     * 根据某个key获取其当前key一直到父级key
     * @param key
     * @return
     */
    public List<KVParentPair> getKeyWithParent(String key){
        List<KVParentPair> list = new ArrayList<>();
        KVPairBO  kvPairBO = kvService.get(KVPairBO.instance(key, null));
        while (!Objects.isNull(kvPairBO)){
            list.add(kvPairBO.convert2ParentPair());
            kvPairBO = kvService.get(KVPairBO.instance().parentKey(kvPairBO.getParentKey()));
        }
        return list;
    }

    /**
     * 批量插入数据
     * @param kvPairBOList
     * @return
     */
    public boolean batchInsert(List<KVPairBO> kvPairBOList){
       return kvService.batchInsert(kvPairBOList);
    }

    public boolean insert(KVPairBO kvPairBO){
        return kvService.insert(kvPairBO);
    }



}
